package com.example.traffic_learning;

import global.MyArrayList;

import java.io.IOException;
import java.util.ArrayList;

import DTO.CorrectAnswerDTO;
import DTO.QuestionDTO;
import DTO.StudyResultDTO;
import adapter.GridAdapterHistoryQuestion;
import adapter.HistoryQuestion;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.MotionEventCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;


public class FragStudy extends Fragment{
    
	private int totalQuestion = 0;
	private int currentQuestion = 1;
	private View view;
	private RelativeLayout myLayout;
	private TextView textQuestionNumber;
	private TextView textQuestion;
	private CheckBox  checkAnswer1;
	private CheckBox  checkAnswer2;
	private CheckBox  checkAnswer3;
	private CheckBox  checkAnswer4;
	private ImageView imageViewQuestion;
	//private MyArrayList<String> questionStudiedSeason = new MyArrayList<String>();;
	String licenseType = null;
	
	ImageView image1;
	ImageView image2;
	ImageView image3;
	ImageView image4;
	MyArrayList<QuestionDTO> questions;
	ArrayList<StudyResultDTO> listStudyResult;
	MyArrayList<ArrayList<UserAnswers>> listState;
	MyArrayList<Boolean> listResultChecked;
	
	AlertDialog.Builder alertDialogBuilder;
	ExpandableHeightGridView gridView;
	AlertDialog alertDialog = null;
	ArrayList<HistoryQuestion> listItem;
	GridAdapterHistoryQuestion apdapter;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		super.onCreateView(inflater, container, savedInstanceState);
		listState = new MyArrayList<ArrayList<UserAnswers>>();
		listResultChecked = new MyArrayList<Boolean>();
		
		view = inflater.inflate(R.layout.activity_study, container, false);
		myLayout = (RelativeLayout)view.findViewById(R.id.layout_question_study);
		
		textQuestionNumber = (TextView)view.findViewById(R.id.text_question_number_study);
		imageViewQuestion = new ImageView(getActivity().getBaseContext());
		imageViewQuestion.setVisibility(View.INVISIBLE);
		
		image1 = (ImageView)view.findViewById(R.id.image_view_result_1_study);
		image2 = (ImageView)view.findViewById(R.id.image_view_result_2_study);
		image3 = (ImageView)view.findViewById(R.id.image_view_result_3_study);
		image4 = (ImageView)view.findViewById(R.id.image_view_result_4_study);
		
		myLayout.addView(imageViewQuestion);
		if(listResultChecked.getElementByTag(currentQuestion) != null)
		{
			if(listResultChecked.getElementByTag(currentQuestion)){
				//ResultCheck(currentQuestion, view);
			}
		}
		Button btnNextQuestion = (Button)view.findViewById(R.id.button_next_question);
		btnNextQuestion.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				nextQuestion(view, myLayout);
			}
		});
		
		Button btnPreviousQuestion = (Button)view.findViewById(R.id.button_previous_question);
		btnPreviousQuestion.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				previousQuestion(view, myLayout);
			}
		});
		
		final View view1 = inflater.inflate(R.layout.grid_history_question, container, false);
		
		Button buttonShowHistory = (Button)view.findViewById(R.id.button_show_history);
		buttonShowHistory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				listStudyResult = StudyResultDTO.getAllStudyResult(getActivity().getBaseContext(), licenseType);
				listItem = new ArrayList<HistoryQuestion>();
				showHistory(view, view1, myLayout);
			}
		});
		checkAnswer1 = (CheckBox)view.findViewById(R.id.checkbox_result_1_study);	 
		checkAnswer2 = (CheckBox)view.findViewById(R.id.checkbox_result_2_study);
		checkAnswer3 = (CheckBox)view.findViewById(R.id.checkbox_result_3_study);
		checkAnswer4 = (CheckBox)view.findViewById(R.id.checkbox_result_4_study);
		showChooseStudy(view, myLayout);
		//myLayout.setClickable(true);
		RelativeLayout layoutStudy = (RelativeLayout)view.findViewById(R.id.layout_study);
		ScrollView scrollView = (ScrollView)view.findViewById(R.id.scroll_question_study);
		ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector();
		layoutStudy.setOnTouchListener(activitySwipeDetector);
		myLayout.setOnTouchListener(activitySwipeDetector);
		scrollView.setOnTouchListener(activitySwipeDetector);
		
		return view;
	}
	private void nextQuestion(View view, RelativeLayout myLayout){
		currentQuestion++;
		if(currentQuestion <= totalQuestion){
			image1.setVisibility(View.INVISIBLE);
			image2.setVisibility(View.INVISIBLE);
			image3.setVisibility(View.INVISIBLE);
			image4.setVisibility(View.INVISIBLE);

			checkAnswer1.setEnabled(true);
			checkAnswer2.setEnabled(true);
			checkAnswer3.setEnabled(true);
			checkAnswer4.setEnabled(true);
			
			StudyResultDTO studyResultDTO = new StudyResultDTO();
			studyResultDTO.setQuestionID(questions.getElementByTag(currentQuestion - 1).getID());
			ArrayList<String>  answerIDs = new ArrayList<String>();
			for(int i = 0; i < listState.getElementByTag(currentQuestion - 1).size(); i++){
				if(listState.getElementByTag(currentQuestion - 1).get(i).isChecked)
					answerIDs.add(listState.getElementByTag(currentQuestion - 1).get(i).getAnswerID());
			}
			if(answerIDs.size() > 0){
				studyResultDTO.setAnswerIDs(answerIDs);
				try{
					StudyResultDTO.insertStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
				}catch(Exception e){}
			}else{
				try{
					StudyResultDTO.deleteStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
				}catch(Exception e){}
			}
			
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);				
		}
		else{
			currentQuestion = totalQuestion;
		}
	}
	private void previousQuestion(View view, RelativeLayout myLayout){
		currentQuestion--;
		if(currentQuestion >= 1){
			image1.setVisibility(View.INVISIBLE);
			image2.setVisibility(View.INVISIBLE);
			image3.setVisibility(View.INVISIBLE);
			image4.setVisibility(View.INVISIBLE);

			checkAnswer1.setEnabled(true);
			checkAnswer2.setEnabled(true);
			checkAnswer3.setEnabled(true);
			checkAnswer4.setEnabled(true);
			
			StudyResultDTO studyResultDTO = new StudyResultDTO();
			studyResultDTO.setQuestionID(questions.getElementByTag(currentQuestion + 1).getID());
			ArrayList<String>  answerIDs = new ArrayList<String>();
			for(int i = 0; i < listState.getElementByTag(currentQuestion + 1).size(); i++){
				if(listState.getElementByTag(currentQuestion + 1).get(i).isChecked)
					answerIDs.add(listState.getElementByTag(currentQuestion + 1).get(i).getAnswerID());
			}
			if(answerIDs.size() > 0){
				studyResultDTO.setAnswerIDs(answerIDs);
				try{
					StudyResultDTO.insertStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
				}catch(Exception e){}
			}else{
				try{
					StudyResultDTO.deleteStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
				}catch(Exception e){}
			}
			
			loadQuestion(view, myLayout);
			loadSavedUserAnswer(currentQuestion);
		}else{
			currentQuestion = 1;
		}
	}
	private int dpToPx(int dp) {
	    DisplayMetrics displayMetrics = getActivity().getBaseContext().getResources().getDisplayMetrics();
	    int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));       
	    return px;
	}
	
	
	 private void loadQuestion(final View view , RelativeLayout layout){
		 ArrayList<UserAnswers> listUserAnswers = new ArrayList<FragStudy.UserAnswers>();
		 for(int i = 0; i < questions.getElementByTag(currentQuestion).getAnswers().size(); i++){
			 listUserAnswers.add(new UserAnswers(questions.getElementByTag(currentQuestion).getAnswers().get(i).getID(), false));
		 }
		 
		 try{
			 StudyResultDTO studyResultDTO = StudyResultDTO.getStudyResultByQuestionID(getActivity(), questions.getElementByTag(currentQuestion).getID(), licenseType);
			 for(int i = 0; i < studyResultDTO.getAnswerIDs().size(); i++){
				 for(int j = 0; j < listUserAnswers.size(); j++){
					 if(listUserAnswers.get(j).getAnswerID().equals(studyResultDTO.getAnswerIDs().get(i))){
						 listUserAnswers.get(j).setChecked(true);
						 listResultChecked.add(Boolean.valueOf(true), currentQuestion);
					 }
				 }
			 }
		 }catch(Exception e){
			 //Log.e("Traffic Learning", e.toString());
		 }	 
		 listState.add(listUserAnswers, currentQuestion);
		 textQuestion = (TextView)view.findViewById(R.id.text_view_question_content_study);
		 //ImageView imageResult = (ImageView)view.findViewById(R.id.image_view_result_1_study);
		 //TODO
		 
		 if(questions.getElementByTag(currentQuestion).getImagePath() != null){
			 
			 LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
					  RelativeLayout.LayoutParams.WRAP_CONTENT);
			 layoutParams.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 imageViewQuestion.setLayoutParams(layoutParams);
			 imageViewQuestion.setPaddingRelative(dpToPx(10), dpToPx(5), dpToPx(5), dpToPx(10));
			 //imageViewQuestion.setScaleX((float)5);
			 //imageViewQuestion.setScaleY((float)5);
			 Drawable image = null;
			 try{
				 Options opts = new BitmapFactory.Options();
				 opts.inDensity = DisplayMetrics.DENSITY_MEDIUM;
				 //image = Drawable.createFromResourceStream(getActivity().getResources(),null,getActivity().getAssets().open(questions.getElementByTag(currentQuestion).getImagePath()), opts);
				 image = Drawable.createFromResourceStream(getResources(), null, getActivity().getAssets().open(questions.getElementByTag(currentQuestion).getImagePath()), null, opts);
			 }catch(IOException e){
				 Log.d("ABCD", e.toString());
			 }
			 imageViewQuestion.setImageDrawable(image);
			 imageViewQuestion.setId(1000);
			 imageViewQuestion.setVisibility(View.VISIBLE);
			 
			 LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
				      											   RelativeLayout.LayoutParams.WRAP_CONTENT);
			 //test.addRule(RelativeLayout.RIGHT_OF, imageResult.getId());
			 layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams1.addRule(RelativeLayout.BELOW, imageViewQuestion.getId());
			 //layoutParams1.topMargin = dpToPx(120);
			 layoutParams1.leftMargin = dpToPx(20);
			 checkAnswer1.setLayoutParams(layoutParams1);
			 
			 LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(dpToPx(18), dpToPx(18));
			 layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams2.addRule(RelativeLayout.BELOW, imageViewQuestion.getId());
			 layoutParams2.topMargin = dpToPx(7);
			 layoutParams2.leftMargin = dpToPx(28);
			 image1.setLayoutParams(layoutParams2);
			 //checkAnswer1.setPadding(dpToPx(0), dpToPx(20), dpToPx(0), dpToPx(0));
			 
		 }else{
			 imageViewQuestion.setVisibility(View.INVISIBLE);
			 LayoutParams layoutParams1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
					   RelativeLayout.LayoutParams.WRAP_CONTENT);
			 //test.addRule(RelativeLayout.RIGHT_OF, imageResult.getId());
			 layoutParams1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 int a = textQuestion.getId();
			 Log.d("ABCD", a + "");
			 layoutParams1.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 layoutParams1.leftMargin = dpToPx(20);
			 checkAnswer1.setLayoutParams(layoutParams1);
			 
			 LayoutParams layoutParams2 = new RelativeLayout.LayoutParams(dpToPx(18), dpToPx(18));
			 layoutParams2.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
			 layoutParams2.addRule(RelativeLayout.BELOW, textQuestion.getId());
			 layoutParams2.topMargin = dpToPx(7);
			 layoutParams2.leftMargin = dpToPx(28);
			 image1.setLayoutParams(layoutParams2);
		 }
		 
		 
		 
		 checkAnswer1.setVisibility(View.INVISIBLE);
		 checkAnswer2.setVisibility(View.INVISIBLE);
		 checkAnswer3.setVisibility(View.INVISIBLE);
		 checkAnswer4.setVisibility(View.INVISIBLE);
		 
		 checkAnswer1.setChecked(false);
		 checkAnswer2.setChecked(false);
		 checkAnswer3.setChecked(false);
		 checkAnswer4.setChecked(false);
		 //textQuestion.setVisibility(View.INVISIBLE);
		 textQuestionNumber.setText("CÂU " + (currentQuestion));
		 textQuestion.setText(questions.getElementByTag(currentQuestion).getContent());
		 if(questions.getElementByTag(currentQuestion).getAnswers().size() == 2){
			 checkAnswer1.setVisibility(View.VISIBLE);
			 checkAnswer1.setText(questions.getElementByTag(currentQuestion).getAnswers().get(0).getContent());
			 checkAnswer1.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(checkAnswer1.isChecked()){
						listState.getElementByTag(currentQuestion).get(0).setChecked(true);
					}else{
						listState.getElementByTag(currentQuestion).get(0).setChecked(false);
					}
				}
			});
			 
			 checkAnswer2.setVisibility(View.VISIBLE);
			 checkAnswer2.setText(questions.getElementByTag(currentQuestion).getAnswers().get(1).getContent());
			 checkAnswer2.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if(checkAnswer2.isChecked()){
							listState.getElementByTag(currentQuestion).get(1).setChecked(true);
						}else{
							listState.getElementByTag(currentQuestion).get(1).setChecked(false);
						}
					}
				});
		 }else{
			 if(questions.getElementByTag(currentQuestion).getAnswers().size() == 3){
				 checkAnswer1.setVisibility(View.VISIBLE);
				 checkAnswer1.setText(questions.getElementByTag(currentQuestion).getAnswers().get(0).getContent());
				 checkAnswer1.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer1.isChecked()){
								listState.getElementByTag(currentQuestion).get(0).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(0).setChecked(false);
							}
						}
					});
				 
				 checkAnswer2.setVisibility(View.VISIBLE);
				 checkAnswer2.setText(questions.getElementByTag(currentQuestion).getAnswers().get(1).getContent());
				 checkAnswer2.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer2.isChecked()){
								listState.getElementByTag(currentQuestion).get(1).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(1).setChecked(false);
							}
						}
					});
				 
				 checkAnswer3.setVisibility(View.VISIBLE);
				 checkAnswer3.setText(questions.getElementByTag(currentQuestion).getAnswers().get(2).getContent());
				 checkAnswer3.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer3.isChecked()){
								listState.getElementByTag(currentQuestion).get(2).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(2).setChecked(false);
							}
						}
					});
			 }else{
				 checkAnswer1.setVisibility(View.VISIBLE);
				 checkAnswer1.setText(questions.getElementByTag(currentQuestion).getAnswers().get(0).getContent());
				 checkAnswer1.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer1.isChecked()){
								listState.getElementByTag(currentQuestion).get(0).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(0).setChecked(false);
							}
						}
					});
				 
				 checkAnswer2.setVisibility(View.VISIBLE);
				 checkAnswer2.setText(questions.getElementByTag(currentQuestion).getAnswers().get(1).getContent());
				 checkAnswer2.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer2.isChecked()){
								listState.getElementByTag(currentQuestion).get(1).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(1).setChecked(false);
							}
						}
					});
				 
				 checkAnswer3.setVisibility(View.VISIBLE);
				 checkAnswer3.setText(questions.getElementByTag(currentQuestion).getAnswers().get(2).getContent());
				 checkAnswer3.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer3.isChecked()){
								listState.getElementByTag(currentQuestion).get(2).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(2).setChecked(false);
							}
						}
					});
				 
				 checkAnswer4.setVisibility(View.VISIBLE);
				 checkAnswer4.setText(questions.getElementByTag(currentQuestion).getAnswers().get(3).getContent());
				 checkAnswer4.setOnClickListener(new View.OnClickListener() {
						
						@Override
						public void onClick(View v) {
							if(checkAnswer4.isChecked()){
								listState.getElementByTag(currentQuestion).get(3).setChecked(true);
							}else{
								listState.getElementByTag(currentQuestion).get(3).setChecked(false);
							}
						}
					});
			 }
		 }
		 Button btnResult = (Button)view.findViewById(R.id.button_result_question);
		 btnResult.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				final int action = MotionEventCompat.getActionMasked(event);
				switch(action){
				case MotionEvent.ACTION_DOWN:
					ResultCheck(currentQuestion, view);
					listResultChecked.add(Boolean.valueOf(true), currentQuestion);
					StudyResultDTO studyResultDTO = new StudyResultDTO();
					studyResultDTO.setQuestionID(questions.getElementByTag(currentQuestion).getID());
					ArrayList<String>  answerIDs = new ArrayList<String>();
					for(int i = 0; i < listState.getElementByTag(currentQuestion).size(); i++){
						if(listState.getElementByTag(currentQuestion).get(i).isChecked)
							answerIDs.add(listState.getElementByTag(currentQuestion).get(i).getAnswerID());
					}
					if(answerIDs.size() > 0){
						studyResultDTO.setAnswerIDs(answerIDs);
						try{
							StudyResultDTO.insertStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
						}catch(Exception e){}
					}else{
						try{
							StudyResultDTO.deleteStudyResult(getActivity().getBaseContext(), studyResultDTO, licenseType);
						}catch(Exception e){}
					}
					break;
				case MotionEvent.ACTION_UP:
					image1.setVisibility(View.INVISIBLE);
					image2.setVisibility(View.INVISIBLE);
					image3.setVisibility(View.INVISIBLE);
					image4.setVisibility(View.INVISIBLE);

					checkAnswer1.setEnabled(true);
					checkAnswer2.setEnabled(true);
					checkAnswer3.setEnabled(true);
					checkAnswer4.setEnabled(true);
					
					loadSavedUserAnswer(currentQuestion);
					break;
				}
				return false;
			}
		});
	 }
	 private void setImageResult(View view, int index, boolean isTrue, boolean isNoneCheck){
		 
		 switch(index){
		 	case 0:
		 		if(isTrue){
		 			image1.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image1.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image1.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image1.setVisibility(View.VISIBLE);
		 		checkAnswer1.setChecked(false);
		 		break;
		 	case 1:
		 		if(isTrue){
		 			image2.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image2.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image2.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image2.setVisibility(View.VISIBLE);
		 		checkAnswer2.setChecked(false);
		 		break;
		 	case 2:
		 		if(isTrue){
		 			image3.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image3.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image3.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image3.setVisibility(View.VISIBLE);
		 		checkAnswer3.setChecked(false);
		 		break;
		 	case 3:
		 		if(isTrue){
		 			image4.setImageResource(R.drawable.blue_tick);
		 		}else{
		 			if(isNoneCheck){
		 				image4.setImageResource(R.drawable.red_tick);
		 			}else{	
		 				image4.setImageResource(R.drawable.red_x);
		 			}
		 		}
		 		image4.setVisibility(View.VISIBLE);
		 		checkAnswer4.setChecked(false);
		 		break;
		 }
	 }
	 
	 private class UserAnswers{
		private String AnswerID;
		private boolean isChecked;
		
		public UserAnswers(String answerID, boolean isChecked){
			this.AnswerID = answerID;
			this.isChecked = isChecked;
		}
		
		public String getAnswerID() {
			return AnswerID;
		}
		@SuppressWarnings("unused")
		public void setAnswerID(String answerID) {
			AnswerID = answerID;
		}
		@SuppressWarnings("unused")
		public boolean isChecked() {
			return isChecked;
		}
		public void setChecked(boolean isChecked) {
			this.isChecked = isChecked;
		}		 
	 }
	 
	 private void loadSavedUserAnswer(int curQuestion){
		 switch (listState.getElementByTag(curQuestion).size()) {
			case 2:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				break;
			case 3:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				checkAnswer3.setChecked(listState.getElementByTag(curQuestion).get(2).isChecked);
				break;
			case 4:
				checkAnswer1.setChecked(listState.getElementByTag(curQuestion).get(0).isChecked);
				checkAnswer2.setChecked(listState.getElementByTag(curQuestion).get(1).isChecked);
				checkAnswer3.setChecked(listState.getElementByTag(curQuestion).get(2).isChecked);
				checkAnswer4.setChecked(listState.getElementByTag(curQuestion).get(3).isChecked);
				break;

		 }
	 }
	 
	private void ResultCheck(int curQuestion, View view){
		int i = 0;
		image1.setVisibility(View.INVISIBLE);
		image2.setVisibility(View.INVISIBLE);
		image3.setVisibility(View.INVISIBLE);
		image4.setVisibility(View.INVISIBLE);
		
		for(UserAnswers userAnswers : listState.getElementByTag(curQuestion)){
				
			for (CorrectAnswerDTO correctAnswer : questions.getElementByTag(curQuestion).getCorrectAnswers()) {
				if(userAnswers.getAnswerID().equals(correctAnswer.getAnswerID()) && userAnswers.isChecked){
					setImageResult(view, i, true, false);
					break;
				}else{
					if(userAnswers.getAnswerID() != correctAnswer.getAnswerID() && userAnswers.isChecked){
						setImageResult(view, i, false, false);
					}else{
						if(userAnswers.getAnswerID().equals(correctAnswer.getAnswerID()) && !userAnswers.isChecked){
							setImageResult(view, i, false, true);
						}
					}
				}
			}
			i++;
		}
		checkAnswer1.setEnabled(false);
		checkAnswer2.setEnabled(false);
		checkAnswer3.setEnabled(false);
		checkAnswer4.setEnabled(false);
	}
	private void showChooseStudy(final View view, final RelativeLayout myLayout){
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
		final ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
		arrAdapter.add("GPLX Hạng A1 , A2");
		arrAdapter.add("GPLX Hạng A3, A4");
		arrAdapter.add("GPLX Hạng B1");
		arrAdapter.add("GPLX Hạng B2, C, D, E, F");
		
		alertDialogBuilder.setCancelable(false).setAdapter(arrAdapter, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch(which){
				case 0:
					licenseType = "A1";
					break;
				case 1:
					licenseType = "A3";
					break;
				case 2:
					licenseType = "B1";
					break;
				case 3:
					licenseType = "B2";
					break;
				}
				//get data
				questions = QuestionDTO.GetQuestionByLicenseType(getActivity().getBaseContext(), licenseType);
				totalQuestion = questions.size();
				listStudyResult = StudyResultDTO.getAllStudyResult(getActivity().getBaseContext(), licenseType);
				ArrayList<String> temp = new ArrayList<String>();
				for(int i = 0; i < listStudyResult.size(); i++){
					temp.add(listStudyResult.get(i).getQuestionID());
				}
				if(listStudyResult.size() > 0){
					String questionID = listStudyResult.get(listStudyResult.size() - 1).getQuestionID();
					for(int i = 1; i <= totalQuestion; i++){
						if(!questionID.equals(questions.getElementByTag(totalQuestion).getID())){
							if(questions.getElementByTag(i).getID().equals(questionID)){
								if(i < totalQuestion)
									currentQuestion = i + 1;
								else{
									currentQuestion = i;
								}
								break;
							}
						}else{
							if(!temp.contains(questions.getElementByTag(i).getID())){
								currentQuestion = i;
								break;
							}
						}
					}
				}
				
				loadQuestion(view, myLayout);
				loadSavedUserAnswer(currentQuestion);
				if(listResultChecked.getElementByTag(currentQuestion) != null)
				{
					if(listResultChecked.getElementByTag(currentQuestion)){
						//ResultCheck(currentQuestion, view);
					}
				}else{
					image1.setVisibility(View.INVISIBLE);
					image2.setVisibility(View.INVISIBLE);
					image3.setVisibility(View.INVISIBLE);
					image4.setVisibility(View.INVISIBLE);
					checkAnswer1.setEnabled(true);
					checkAnswer2.setEnabled(true);
					checkAnswer3.setEnabled(true);
					checkAnswer4.setEnabled(true);
				}
			}
		});
		
		AlertDialog alertDialog = alertDialogBuilder.create();
		alertDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface arg0, int arg1, KeyEvent arg2) {
				getActivity().finish();
				return false;
			}
		});
		alertDialog.show();
	}
	
	private void showHistory(final View view, View view1, final RelativeLayout myLayout){
		alertDialogBuilder = new AlertDialog.Builder(getActivity());
		alertDialogBuilder.setCancelable(false)
				   .setPositiveButton("Trở về", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
				   }).setNegativeButton("Xóa", new DialogInterface.OnClickListener() {
					
						@Override
						public void onClick(DialogInterface dialog, int which) {
							AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
							
							alertDialogBuilder.setMessage("Bạn có chắc muốn xóa tất cả kết quả học?")
									   .setCancelable(false)
									   .setPositiveButton("Có", new DialogInterface.OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												StudyResultDTO.deleteByLicenseType(getActivity(), licenseType);
												listState.removeAll();
												listResultChecked.removeAll();
												currentQuestion = 1;
												//questionStudiedSeason.removeAll();
												loadQuestion(view, myLayout);
												alertDialog.show();
												listStudyResult = StudyResultDTO.getAllStudyResult(getActivity().getBaseContext(), licenseType);
												listItem = new ArrayList<HistoryQuestion>();
												Boolean isStudied = false;
												Boolean isTrue = false;
												listStudyResult = StudyResultDTO.getAllStudyResult(getActivity().getBaseContext(), licenseType);
												for(int i = 1; i <= questions.size(); i++){
													isStudied = false;
													isTrue = false;
													for(int j = 0; j < listStudyResult.size(); j++){
														if(questions.getElementByTag(i).getID().equals(listStudyResult.get(j).getQuestionID())){
															isStudied = true;
															break;
														}
													}
													HistoryQuestion historyQuestion = new HistoryQuestion();
													historyQuestion.setQuestionNo("Câu " + i);
													historyQuestion.setIsChecked(isStudied);
													historyQuestion.setIsTrue(isTrue);
													listItem.add(historyQuestion);
												}
												apdapter = new GridAdapterHistoryQuestion(getActivity().getBaseContext(), listItem);
												gridView.setAdapter(apdapter);
											}
									   })
									   .setNegativeButton("Không", new DialogInterface.OnClickListener() {
										
											@Override
											public void onClick(DialogInterface dialog, int which) {
												dialog.cancel();
												alertDialog.show();
											}
										});
							
							AlertDialog alertDialog = alertDialogBuilder.create();
							alertDialog.show();
						}
				   });
		gridView = (ExpandableHeightGridView)view1.findViewById(R.id.expanable_gridview_history);
		
		Boolean isStudied = false;
		Boolean isTrue = false;
		listStudyResult = StudyResultDTO.getAllStudyResult(getActivity().getBaseContext(), licenseType);
		for(int i = 1; i <= questions.size(); i++){
			isStudied = false;
			isTrue = false;
			for(int j = 0; j < listStudyResult.size(); j++){
				if(questions.getElementByTag(i).getID().equals(listStudyResult.get(j).getQuestionID())){
					isStudied = true;
					break;
				}
			}
			HistoryQuestion historyQuestion = new HistoryQuestion();
			historyQuestion.setQuestionNo("Câu " + i);
			historyQuestion.setIsChecked(isStudied);
			historyQuestion.setIsTrue(isTrue);
			listItem.add(historyQuestion);
		}
		apdapter = new GridAdapterHistoryQuestion(getActivity().getBaseContext(), listItem);
		gridView.setAdapter(apdapter);
		gridView.setExpanded(true);
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long arg3) {
				currentQuestion = index + 1;
				loadQuestion(view, myLayout);
				loadSavedUserAnswer(currentQuestion);
				if(listResultChecked.getElementByTag(currentQuestion) != null)
				{
					//return gestureDetector.onTouchEvent(event);
				}else{
					image1.setVisibility(View.INVISIBLE);
					image2.setVisibility(View.INVISIBLE);
					image3.setVisibility(View.INVISIBLE);
					image4.setVisibility(View.INVISIBLE);
					checkAnswer1.setEnabled(true);
					checkAnswer2.setEnabled(true);
					checkAnswer3.setEnabled(true);
					checkAnswer4.setEnabled(true);
				}
				if(alertDialog != null){
					alertDialog.dismiss();
				}
			}
		});

		ScrollView scrollView = (ScrollView)view1.findViewById(R.id.scroolView_history);
		try{
			alertDialogBuilder.setView(scrollView);
		}catch(Exception e){}
		if(alertDialog == null)
			alertDialog = alertDialogBuilder.create();
		alertDialog.show();
	}
	class ActivitySwipeDetector implements View.OnTouchListener {

		static final String logTag = "ActivitySwipeDetector";
		static final int MIN_DISTANCE = 100;
		private float downX, downY, upX, upY;

		public boolean onTouch(View v, MotionEvent event) {
		    switch(event.getAction()){
		        case MotionEvent.ACTION_DOWN: {
		            downX = event.getX();
		            downY = event.getY();
		            return true;
		        }
		        case MotionEvent.ACTION_UP: {
		            upX = event.getX();
		            upY = event.getY();
		            float deltaX = downX - upX;
		            float deltaY = downY - upY;
			        if(Math.abs(deltaX) > Math.abs(deltaY)){
			            if(Math.abs(deltaX) > MIN_DISTANCE){
			                if(deltaX < 0) { 
			                	previousQuestion(view, myLayout); 
			                	return true; 
			                }
			                if(deltaX > 0) { 
			                	nextQuestion(view, myLayout); 
			                	return true; 
			                }
			            }
			        } 
		        }
		        return false;
		    }
			return false;
		}
	}
}


